<?php
/**
 * Created by PhpStorm.
 * User: wdt
 * Date: 2016/3/18
 * Time: 18:02
 */

namespace front\modules\web\controllers;


use Yii;
use front\controllers\WebBaseController;
use goods\services\CartService;
use yii\helpers\ArrayHelper;
use goods\services\ProductService;
use yii\web\Cookie;
class CartController extends WebBaseController{

    public $layout = 'main';
    /**
     * 添加商品到购物车
     * @return array
     */
    public function actionAdd()
    {
        if($this->getUserId() == 0){
            WebBaseController::getAjaxData(3,'请登录','',$_GET['callback']);
        }

        $data = \Yii::$app->request->get();
        $data['shop_id'] = $this->shop_id;
        $data['uid'] = $this->getUserId();
        if (empty($data['product_id'])) {
            WebBaseController::getAjaxData(4,'未传递product_id','',$_GET['callback']);
        }
        if (empty($data['num'])) {
            WebBaseController::getAjaxData(5,'未传递num','',$_GET['callback']);
        }
        $ret = CartService::addCart($data);

        if($ret['code'] == 1){
            WebBaseController::getAjaxData(6,'库存不足','',$_GET['callback']);
        }
        if($ret['code']==0){
            $cartCount = CartService::cartCount($this->shop_id,$this->getUserId());   //购物车数量
            WebBaseController::getAjaxData(1,$ret['message'],'',$_GET['callback'],$cartCount);
        }
    }

    /**
     * 修改购物车
     * @return array
     */
    public function actionUpdate()
    {
        $data = \Yii::$app->request->post();
        if (empty($data['shop_id'])) {
            WebBaseController::getAjaxData(2,'未传递shop_id');
        }
        $data['uid'] = $this->getUserId();
        if (empty($data['product_id'])) {
            WebBaseController::getAjaxData(4,'未传递product_id');
        }
        if (empty($data['num'])) {
            WebBaseController::getAjaxData(5,'未传递num');
        }
        $ret = CartService::updateCart($data);
        if ($ret['code'] == 0) {
            WebBaseController::getAjaxData(1,'更新购物车成功');
        }
        WebBaseController::getAjaxData(6,'更新购物车失败');
    }

    /**
     * 清空购物车
     * @return array
     */
    public function actionEmpty()
    {
        $data = \Yii::$app->request->post();
        if (empty($data['shop_id'])) {
            WebBaseController::getAjaxData(2,'未传递shop_id');
        }
        $data['uid'] = $this->getUserId();
        $ret = CartService::emptyCart($data['shop_id'],$data['uid']);
        if ($ret['code'] == 0) {
            WebBaseController::getAjaxData(1,'清空购物车成功');
        }
        WebBaseController::getAjaxData(4,'清空购物车失败');
    }

    /**
     * 删除购物车商品
     * @return array
     */
    public function actionDelete()
    {
        $data = \Yii::$app->request->get();
        $res = $this->getCart($data['oid']);
        $data['uid'] = $this->getUserId();
        foreach($res as $k=>$v){
            $ret = CartService::deleteProduct($v['shop_id'],$data['uid'],$v['product_id']);
        }
        if ($ret['code'] == 0) {
            WebBaseController::getAjaxData(1,'删除购物车商品成功','',$data['callback']);
        }
        WebBaseController::getAjaxData(5,'删除购物车商品失败','',$data['callback']);
    }

    function getCart($data){
        foreach($data as $k=>$v){
            $arr[] = explode(',',$v);
        }
        foreach($arr as $key => $val){
            $res[$key]['product_id'] = $val[0];
            $res[$key]['shop_id'] = $val[1];
        }
        return $res;
    }

    /**
     * 查看购物车
     * @return array
     */
    public function actionView()
    {
        if($this->getUserId() == 0){
            return $this->redirect('/web/user/login');
        }
        $info = CartService::view($this->shop_id,$this->getUserId());
        $info = ArrayHelper::toArray($info);
        foreach($info as $k=>$v){
            $info[$k]['data']['item_attrText_map'] =  isset($v['product_id']) ? $this->getProoductAttr($v['product_id']) : '';
            $info[$k]['created_at'] =isset($v['created_at']) ? date('Y-m-d H:i:s',$v['created_at']): date('Y-m-d H:i:s',time());
            $info[$k]['updated_at'] =isset($v['updated_at']) ? date('Y-m-d H:i:s',$v['updated_at']) : date('Y-m-d H:i:s',time());
            $info[$k]['data']['thumb'][0] =isset($v['data']['thumb'][0]) ? $v['data']['thumb'][0] . '@1e_1c_0o_0l_200h_200w_100q.jpg':'';
            $info[$k]['data']['goods_price'] = isset($v['product_id']) ?  $this->getProoduct($v['product_id']) : "";
        }
        $cookies = Yii::$app->response->cookies;
        $cookies->remove('order');
        $cookies->remove('addr');
        $cookies->remove('mobile');
        return  $this->render('view',['list'=>$info]);
    }


    /**
     * 获取价格 本来可以写成一个方法，但是这个方法是后写的
     */
    function getProoduct($pid){
        $res = ProductService::ProductInfo($pid);
        if($res['result']){
            $res['result'] = ArrayHelper::toArray($res['result']);
            $res['price'] = isset($res['result']['productInfo']['price'])?$res['result']['productInfo']['price']:'0.00';
            $arr = $res['price'];
        }
        return $arr;
    }

    /**
     * 属性
     */

    function getProoductAttr($pid){
        $res = ProductService::ProductInfo($pid);
        if($res['result']){
            $res['result'] = ArrayHelper::toArray($res['result']);
            $res['item_attrText_map'] = isset($res['result']['productInfo']['item_attrText_map']) ? $res['result']['productInfo']['item_attrText_map']:array();
            unset($res['item_attrText_map']['product_id']);
            $arr = $res['item_attrText_map'];
        }
        $arr = $this->setAttr($arr);
        return $arr;
    }

    /**
     * 组合属性
     */
    function setAttr($data){
        $res='';
        foreach($data as $k=>$v){
            $res.=$k.':'.$v.'<br/>';
        }
        return $res;
    }

    /**
     * 价格
     *
     */
    public function actionSubmit()
    {
        $data = \Yii::$app->request->get();
        $data['product_id'] = intval($data['id']);
        $data['funcName'] = $data['callback'];
        if(!$data['product_id']){
            WebBaseController::getAjaxData('2','商品不存在');
        }
        $res = ProductService::ProductInfo($data['product_id']);
        if($res['result']){
            $res['result'] = ArrayHelper::toArray($res['result']);
            $res['price'] = isset($res['result']['productInfo']['price']) ? $res['result']['productInfo']['price'] : 0;
            $arr['price'] = $res['price'];
        }
        WebBaseController::getAjaxData(1,'获取成功',$arr,$data['funcName']);
    }

    /**
     * 价格
     * Array
    (
    [id] => 1000205
    [oId] => Array
    (
    [0] => 1000201,1001
    [1] => 1000202,1001
    [2] => 1000205,1001
    )

    [num] => 2
    [callback] => jsonp2
    )


     *
     */
    public function actionSubmitnum()
    {
        $data = \Yii::$app->request->get();
        $data['product_id'] = intval($data['id']);
        $data['funcName'] = $data['callback'];
        if(!$data['product_id']){
            WebBaseController::getAjaxData('2','商品不存在');
        }

        $arr['product_id'] = $data['product_id'];
        $arr['shop_id'] = $this->shop_id;
        $arr['uid'] = $this->getUserId();
        $arr['num'] = $data['num'];
        CartService::updateCart($arr);
        $res = ProductService::ProductInfo($data['product_id']);
        if($res['result']){
            $res['result'] = ArrayHelper::toArray($res['result']);
            $res['stock'] = isset($res['result']['productInfo']['stock']) ? $res['result']['productInfo']['stock'] : 0;
            $res['price'] =isset($res['result']['productInfo']['price']) ? $res['result']['productInfo']['price'] : 0;
            $rest['price'] = $res['price'];
            $rest['min'] = 1;
            $rest['max'] = $res['stock'];
        }
        WebBaseController::getAjaxData(1,'获取成功',$rest,$data['funcName']);
    }

    /**
     * 计算总价
     */
    function actionSubmitcount(){
        $data = \Yii::$app->request->get();

        if(!$data['pids']){
            WebBaseController::getAjaxData(2,'产品不存在');
        }
        $pids = explode(',', $data['pids']);
        $nums = explode(',', $data['nums']);
        $total = $count = 0;
        foreach($pids as $i => $v){
            //每件商品的价格
            //CartService::updateCart();
            $res[$i] = ProductService::ProductInfo($v);
            $res[$i] = ArrayHelper::toArray($res[$i]['result']);
            $arr[$i] = isset($res[$i]['productInfo']['price']) ? $res[$i]['productInfo']['price'] : 0;
            $total += $arr[$i] * $nums[$i];
            $count += $nums[$i];
        }
        $rest['total'] = $total;
        $rest['procount'] = $count;
        WebBaseController::getAjaxData(1,'获取成功',$rest,$data['callback']);
    }




    /**
     * 结算
     * 前台参数格式：如两个商品 $cartProduct[0]=array('product_id'=> '131411','num'=>'1','data'=> '15151'),
     */
    public function actionSubmitinfo()
    {
        $data = \Yii::$app->request->get();
        if (!is_array($data) || count($data) == 0) {
            WebBaseController::getAjaxData(2,'参数不合法');
        }
        $total_price = 0;
        foreach ($data as $k=>$v) {
            $data[$k]['price'] = ProductService::getPrice($v['product_id']);
            $data[$k]['price'] = ArrayHelper::toArray($data[$k]['price']);
            $data[$k]['price'] = $data[$k]['price']['price'];
            $total_price = $total_price + ($data[$k]['price'] * $data[$k]['num']);
        }
        return ['data' => $data, 'total_price' => $total_price];
    }




}